package br.com.fiap.sas.converter;

import java.text.NumberFormat;
import java.util.regex.Pattern;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

public class MyDoubleConverter implements Converter {  
	  
	public Object getAsObject(FacesContext context, UIComponent component, String value) {  
        
        if(value == null || value.trim().equals("")){
            return 0.0D;
         }
            Boolean matcher = Pattern.matches("[0-9]+([.,][0-9]{2}+)?",value);
                if(matcher){
                    value = value.replace(",", ".");
                    return new Double(value);
                }
                else
                	throw new ConverterException();
	}
    public String getAsString(FacesContext context, UIComponent component, Object object) {
          
        if(object == null || object.toString().trim().equals("")){
             return "0.00";
         }
         else{
        	 NumberFormat nF = NumberFormat.getInstance(FacesContext.getCurrentInstance().getViewRoot().getLocale());
             nF.setMaximumFractionDigits(2);
             return nF.format(Double.valueOf(object.toString()));
         }
    }
}